#pragma once
#include "tcp_socket.hpp"

typedef void(*Handler)(const std::string& req,std::string* resp);

class TcpServer
{
	private:
		TcpSocket listen_sock_;
		std::string ip_;
		uint64_t port_;
	public:
		TcpServer(const std::string& ip,uint16_t port):ip_(ip),port_(port)
	{}
		bool Start(Handler handler)
		{
			listen_sock_.Socket();
			listen_sock_.Bind(ip_,port_);
			listen_sock_.Listen(5);

			while(1)
			{
				TcpSocket new_sock;
				std::string ip;
				uint16_t port = 0;
				if(!listen_sock_.Accept(&new_sock,&ip,&port))
					continue;
				std::cout<<"client "<<ip.c_str()<<":"<<port<<std::endl;
				while(1)
				{
					std::string req;
					bool ret = new_sock.Recv(&req);
					if(!ret)
					{
						std::cout<<"client disconnect!"<<std::endl;
						new_sock.Close();
						break;
					}
					std::string resp;
					handler(req,&resp);

					new_sock.Send(resp);
					std::cout<<ip.c_str()<<":"<<port<<"req:"<<req.c_str()<<" resp:"<<resp.c_str()<<std::endl;
				}
			}
			return true;
		}
};



